<template>
	<u-popup :show="show" :round="10" @close="show=false">
		<view class="container">
			<view class="flex justify-between items-center">
				<view class="flex items-center">
					<view class="text-[32rpx] text-[#101010] mr-[60rpx]">头像</view>
					<u-avatar :src="src" size="60"></u-avatar>
				</view>
                <view>
                    <button type="primary" plain size="mini" open-type="chooseAvatar"
                            @chooseavatar="onChooseAvatar">选择图像</button>
                </view>
			</view>
			<view class="flex items-center mt-[46rpx]">
				<view class="text-[32rpx] text-[#101010] mr-[60rpx]">昵称</view>
				<view>
					<input class="nameInput" type="nickname" v-model="username" placeholder="请输入昵称" />
				</view>
			</view>
			<view class="w-4/5 mx-auto my-[46rpx]">
				<u-button type="primary" @click="confirm">确定</u-button>
			</view>
		</view>
	</u-popup>
</template>

<script>
	import {
		mapMutations
	} from "vuex";
	import {
		getMyInfoApi,
		updateWxInfo
	} from "@/sheep/api/index";
	import {
		baseUrl
	} from "@/sheep/request/baseUrl";
	export default {
		data() {
			return {
				show: false,
				src: "",
				username: "",
			};
		},
		methods: {
			...mapMutations({
				setUserInfo: "user/setUserInfo",
			}),
			onChooseAvatar(e) {
				// this.src = e.detail.avatarUrl;
				let self = this;
				let {
					avatarUrl
				} = e.detail;
				uni.showLoading({
					title: '加载中'
				});
				uni.uploadFile({
					url: baseUrl + '/resource/oss/upload',
					filePath: avatarUrl,
					name: 'file',
					header: {
						Authorization: 'Bearer ' + uni.getStorageSync('token'),
						clientId: "be7052a7e4f802c20df10a8d131adb12"
					},
					success: uploadFileRes => {
						// 注意：这里返回的uploadFileRes.data 为JSON 需要自己去转换
						let data = JSON.parse(uploadFileRes.data);
						if (data.code === 200) {
							self.src = data.data.url;
						}
					},
					fail: (error) => {
						uni.showToast({
							title: error,
							duration: 2000
						});
					},
					complete: () => {
						uni.hideLoading();
					}
				})

			},
			async confirm() {
				const {
					code
				} = await updateWxInfo(this.username, this.src);
				if (code === 200) {
					const {
						data
					} = await getMyInfoApi();
					this.setUserInfo(data);
                    this.$emit('handleRefresh')
					this.show = false;
				}
			},
			open(name, url) {
				this.username = name;
				this.src = url;
				this.show = true;
			},
		},
	};
</script>

<style lang="scss" scoped>
	.container {
		padding: 46rpx 36rpx 30rpx;
	}

	button {
		margin: 0;
	}
</style>
